package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/*
    工具类：session
 */
public class MapperUtil {
    //设置全局变量
    private static SqlSessionFactory factory = null;

    private MapperUtil(){}

    //设置静态代码块
    static {
        InputStream is = null;
        try {
            //1、读取mybatis核心配置文件的信息:运行环境，映射配置文件信息
            is = Resources.getResourceAsStream("sql.xml");
            //2、构建SqlSessionFactory对象(构建者模式)
             factory = new SqlSessionFactoryBuilder().build(is);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取session
    public static SqlSession getsession() {
        //3、获取SqlSession对象
        return  factory.openSession();
    }

    //释放资源
    public static void close(SqlSession session) {
        //事务提交(查询事务用事务，没事务就算了)
        session.commit();
        //释放资源
        session.close();
    }
}
